﻿using Dapper;
using Microsoft.AspNetCore.Mvc;
using System.Data.SqlClient;
using System.Data;
using Xm.Entity;
using Xm.Models;
using Newtonsoft.Json;
using Autofac.Core;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace Xm.Controllers
{
    public class configController : Controller
    {
        private readonly ITestLogin _text; // 使用接口类型

        // 通过构造函数注入
        public configController(ITestLogin text)
        {
            _text = text; // 初始化 text 对象
        }
        
        
        [HttpGet]
        public IActionResult major_kind_update()
        {
            return View();
        }
        [HttpPost]
        [Route("config/major_kind_update")]
        public async Task<IActionResult> UpdateMajorKind([FromBody] config_major_kind dz)
        {
            if (dz == null)
            {
                return BadRequest(new { success = false, message = "数据为空或格式错误" });
            }

            if (ModelState.IsValid)
            {
                int result = await _text.major_kind_update(dz);
                return Ok(new { success = result > 0, message = result > 0 ? "更新成功" : "更新失败，请重试" });
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                return BadRequest(new { success = false, message = "验证失败", errors });
            }
        }
        public IActionResult major_kindadd()
        {
            return View();
        }
        [HttpGet]
        public IActionResult major_kind_add()
        {
            return View();
        }

        // 处理表单提交的POST方法
        [HttpPost]
        [Route("config/major_kind_add")]
        public async Task<IActionResult> major_kind_add(config_major_kind dz)
        {
            if (dz == null)
            {
                // 若模型为null，可能是请求体为空或格式错误
                return BadRequest(new { success = false, message = "数据为空或格式错误" });
            }

            if (ModelState.IsValid)
            {
                int result = await _text.major_kind_add(dz);
                return Ok(new { success = result > 0, message = "操作成功" });
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                return BadRequest(new { success = false, message = "验证失败", errors });
            }
        }
        public IActionResult config_public_char()
        {
            return View();
        }
        // 获取添加页面的GET方法
            [HttpGet]
            public IActionResult public_char_add()
            {
                return View();
            }

        // 处理表单提交的POST方法
        [HttpPost]
        [Route("config/public_char_add")]
        public async Task<IActionResult> public_char_add_post(config_public_char dz)
        {
            if (dz == null)
            {
                // 若模型为null，可能是请求体为空或格式错误
                return BadRequest(new { success = false, message = "数据为空或格式错误" });
            }

            if (ModelState.IsValid)
            {
                int result = await _text.public_charinsert(dz);
                return Ok(new { success = result > 0, message = "操作成功" });
            }
            else
            {
                var errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                return BadRequest(new { success = false, message = "验证失败", errors });
            }
        }
        [HttpGet]
        public async Task<IActionResult> config_public_charDelete()
        {

            return View();
        }

        [HttpDelete]
        public async Task<IActionResult> config_public_charDelete(int id)
        {

            var i = await _text.config_public_charDelete(id);
            if (i > 0)
            {
                return RedirectToAction("config_public_char");
            }
            else
            {
                return RedirectToAction("config_public_char");
            }


        }
        public IActionResult config_public_charfy(int currentPage, int pageSize)
        {
            //调用分页的存储过程
            string connectionStr = "server=.;database=HR_DB;uid=sa;pwd=123456;";
            using (SqlConnection conn = new SqlConnection(connectionStr))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@tableName", "pbc_id");
                param.Add("@keyName", "config_public_char");
                param.Add("@currentPage", currentPage);
                param.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYe] @pageSize, @tableName, @keyName, @currentPage, @rows out";
                List<config_public_char> list = conn.Query<config_public_char>(sql, param).ToList();

                FenYe<config_public_char> fenYecs = new FenYe<config_public_char>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("rows");
                //return fenYecs;
                return Json(fenYecs);
            }


        }
        public IActionResult config_major1()
        {
            return View();
        }
        public IActionResult major_add()
        {
            return View();
        }
        [HttpPost] // 显式声明支持POST请求
        [Route("config/major_add")]
        public async Task<IActionResult> major_add([FromBody] config_major dz)
        {
            if (!ModelState.IsValid)
            {
                // 记录模型验证错误
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();

                Console.WriteLine($"模型验证错误: {string.Join("; ", errors)}");
                return BadRequest(new { success = false, message = "输入数据格式不正确", errors });
            }

            if (_text == null)
            {
                return StatusCode(500, new { success = false, message = "服务未初始化" });
            }

            try
            {

                int result = await _text.config_majorinsert(dz);
                return Ok(new { success = result > 0, message = result > 0 ? "成功" : "失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"插入异常: {ex.ToString()}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }

        }
        public IActionResult config_major_kind()
        {
            return View();
        }
        
         [HttpGet]
        public async Task<IActionResult> config_major_kindDelete()
        {

            return View();
        }

        [HttpDelete]
        public async Task<IActionResult> config_major_kindDelete(int id)
        {

            var i = await _text.config_major_kindDelete(id);
            if (i > 0)
            {
                return RedirectToAction("config_major_kind");
            }
            else
            {
                return RedirectToAction("config_major_kind");
            }


        }
        public IActionResult config_major_kindfy(int currentPage, int pageSize)
        {
            //调用分页的存储过程
            string connectionStr = "server=.;database=HR_DB;uid=sa;pwd=123456;";
            using (SqlConnection conn = new SqlConnection(connectionStr))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@tableName", "mfk_id");
                param.Add("@keyName", "config_major_kind");
                param.Add("@currentPage", currentPage);
                param.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYe] @pageSize, @tableName, @keyName, @currentPage, @rows out";
                List<config_major_kind> list = conn.Query<config_major_kind>(sql, param).ToList();

                FenYe<config_major_kind> fenYecs = new FenYe<config_major_kind>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("rows");
                //return fenYecs;
                return Json(fenYecs);
            }


        }
        public IActionResult config_major()
        {
            return View();
        }
        [HttpGet]
        public async Task<IActionResult> config_majorDelete()
        {

            return View();
        }

        [HttpDelete]
        public async Task<IActionResult> config_majorDelete(int id)
        {

            var i = await _text.config_majorDelete(id);
            if (i > 0)
            {
                return RedirectToAction("config_major");
            }
            else
            {
                return RedirectToAction("config_major");
            }


        }
        public IActionResult config_majorfy(int currentPage, int pageSize)
        {
            //调用分页的存储过程
            string connectionStr = "server=.;database=HR_DB;uid=sa;pwd=123456;";
            using (SqlConnection conn = new SqlConnection(connectionStr))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@tableName", "mak_id");
                param.Add("@keyName", "config_major");
                param.Add("@currentPage", currentPage);
                param.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYe] @pageSize, @tableName, @keyName, @currentPage, @rows out";
                List<config_major> list = conn.Query<config_major>(sql, param).ToList();

                FenYe<config_major> fenYecs = new FenYe<config_major>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("rows");
                //return fenYecs;
                return Json(fenYecs);
            }


        }
        public IActionResult config_file_third_kind()
        {
            return View();
        }
        [HttpGet]
        public IActionResult thirdUpdate()
        {
            return View();
        }
        [HttpPost]
        [HttpPut] // 同时支持POST和PUT
        [Route("config/thirdUpdate")]
        public async Task<IActionResult> thirdUpdate([FromBody] config_file_third_kind dz) // 修正类型
        {
            try
            {
                if (dz == null)
                {
                    return BadRequest(new { success = false, message = "数据为空" });
                }

                // 判断是新增还是修改（根据fsk_id是否有值）
                bool isUpdate = dz.ftk_id > 0;
                int result = 0;

                if (isUpdate)
                {
                    result = await _text.thirdupdate(dz); // 修改操作
                }
                else
                {
                    // 新增操作（需要在_text中添加对应的新增方法）
                    result = await _text.thirdupdate(dz);
                }

                return result > 0
                    ? Ok(new { success = true, message = isUpdate ? "修改成功" : "新增成功" })
                    : Ok(new { success = false, message = isUpdate ? "修改失败" : "新增失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新异常: {ex.ToString()}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }
        [HttpGet]
        public async Task<IActionResult> thirdDelete()
        {

            return View();
        }

        [HttpDelete]
        public async Task<IActionResult> thirdDelete(int id)
        {

            var i = await _text.thirdDelete(id);
            if (i > 0)
            {
                return RedirectToAction("config_file_third_kind");
            }
            else
            {
                return RedirectToAction("config_file_third_kind");
            }


        }
        [HttpGet]
        public IActionResult thirdinsert()
        {
            return View();
        }
        [HttpPost] // 显式声明支持POST请求
        [Route("config/thirdinsert")]
        public async Task<IActionResult> thirdinsert([FromBody] config_file_third_kind dz)
        {
            if (!ModelState.IsValid)
            {
                // 记录模型验证错误
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();

                Console.WriteLine($"模型验证错误: {string.Join("; ", errors)}");
                return BadRequest(new { success = false, message = "输入数据格式不正确", errors });
            }

            if (_text == null)
            {
                return StatusCode(500, new { success = false, message = "服务未初始化" });
            }

            try
            {
                
                int result = await _text.thirdInsert(dz);
                return Ok(new { success = result > 0, message = result > 0 ? "成功" : "失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"插入异常: {ex.ToString()}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
            
        }
        public IActionResult thirdfy(int currentPage, int pageSize)
        {
            //调用分页的存储过程
            string connectionStr = "server=.;database=HR_DB;uid=sa;pwd=123456;";
            using (SqlConnection conn = new SqlConnection(connectionStr))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@tableName", "ftk_id");
                param.Add("@keyName", "config_file_third_kind");
                param.Add("@currentPage", currentPage);
                param.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYe] @pageSize, @tableName, @keyName, @currentPage, @rows out";
                List<config_file_third_kind> list = conn.Query<config_file_third_kind>(sql, param).ToList();

                FenYe<config_file_third_kind> fenYecs = new FenYe<config_file_third_kind>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("rows");
                //return fenYecs;
                return Json(fenYecs);
            }


        }

        public IActionResult config_file_second_kind()
        {
            return View();
        }
        
        [HttpGet]
        public async Task<IActionResult> secondUpdate()
        {

            return View();
        }
        [HttpPost]
        [HttpPut] // 同时支持POST和PUT
        [Route("config/secondUpdate")]
        public async Task<IActionResult> secondUpdate([FromBody] config_file_second_kind dz) // 修正类型
        {
            try
            {
                if (dz == null)
                {
                    return BadRequest(new { success = false, message = "数据为空" });
                }

                // 判断是新增还是修改（根据fsk_id是否有值）
                bool isUpdate = dz.fsk_id > 0;
                int result = 0;

                if (isUpdate)
                {
                    result = await _text.secondupdate(dz); // 修改操作
                }
                else
                {
                    // 新增操作（需要在_text中添加对应的新增方法）
                    result = await _text.secondupdate(dz);
                }

                return result > 0
                    ? Ok(new { success = true, message = isUpdate ? "修改成功" : "新增成功" })
                    : Ok(new { success = false, message = isUpdate ? "修改失败" : "新增失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新异常: {ex.ToString()}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }
        [HttpGet]
        public async Task<IActionResult> secondDelete()
        {

            return View();
        }

        [HttpDelete]
        public async Task<IActionResult> secondDelete(int id)
        {   

            var i = await _text.secondDelete(id);
            if (i > 0)
            {
                return RedirectToAction("config_file_second_kind");
            }
            else
            {
                return RedirectToAction("config_file_second_kind");
            }


        }
        [HttpGet]
        public IActionResult secondinsert() // 对应视图 /Views/Config/Insert.cshtml
        {
            return View();
        }


        [HttpPost]
        [Route("config/secondinsert")] 
        public async Task<IActionResult> secondinsert([FromBody] config_file_second_kind dz)
        {
            if (!ModelState.IsValid)
            {
                // 记录模型验证错误
                var errors = ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .ToList();

                Console.WriteLine($"模型验证错误: {string.Join("; ", errors)}");
                return BadRequest(new { success = false, message = "输入数据格式不正确", errors });
            }

            if (_text == null)
            {
                return StatusCode(500, new { success = false, message = "服务未初始化" });
            }

            try
            {
                // 添加日志记录，确认dz对象是否为null
                //Console.WriteLine($"接收到的dz对象: {dz != null ? "非空" : "空"}");
                if (dz != null)
                {
                    Console.WriteLine($"first_kind_id: {dz.first_kind_id}");
                    Console.WriteLine($"second_kind_name: {dz.second_kind_name}");
                    // 其他需要检查的属性
                }

                int result = await _text.secondinsert(dz);
                return Ok(new { success = result > 0, message = result > 0 ? "成功" : "失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"插入异常: {ex.ToString()}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }
        public IActionResult secondfy(int currentPage, int pageSize)
        {
            //调用分页的存储过程
            string connectionStr = "server=.;database=HR_DB;uid=sa;pwd=123456;";
            using (SqlConnection conn = new SqlConnection(connectionStr))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@tableName", "fsk_id");
                param.Add("@keyName", "config_file_second_kind");
                param.Add("@currentPage", currentPage);
                param.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYe] @pageSize, @tableName, @keyName, @currentPage, @rows out";
                List<config_file_second_kind> list = conn.Query<config_file_second_kind>(sql, param).ToList();

                FenYe<config_file_second_kind> fenYecs = new FenYe<config_file_second_kind>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("rows");
                //return fenYecs;
                return Json(fenYecs);
            }


        }
        public IActionResult file_first_kind()
        {
            return View();
        }
        [HttpGet]
        public IActionResult Update() // 对应视图 /Views/Config/Insert.cshtml
        {
            
            return View();
        }
        [HttpPost]
        [Route("config/Update")]
        public async Task<IActionResult> Update([FromBody] config_file_first_kind dz)
        {
            try
            {
                // 调试输出接收到的数据
                Console.WriteLine($"接收到的数据: {JsonConvert.SerializeObject(dz)}");

                if (dz == null)
                {
                    Console.WriteLine("错误: 接收到的数据为空");
                    return BadRequest(new { success = false, message = "数据为空" });
                }

                int result = await _text.configupdate(dz);
                return result > 0
                    ? Ok(new { success = true, message = "修改成功" })
                    : Ok(new { success = false, message = "修改失败" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"更新异常: {ex.ToString()}");
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }
        }
        [HttpGet]
        public async Task<IActionResult> Delete()
        {

            return View();
        }
        
        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {

            var i = await _text.configDelete(id);
            if (i > 0)
            {
                return RedirectToAction("file_first_kind");
            }
            else
            {
                return RedirectToAction("file_first_kind");
            }


        }
        [HttpGet]
        public IActionResult insert() // 对应视图 /Views/Config/Insert.cshtml
        {
            return View();
        }

        // POST 方法：处理 API 请求（需明确路由）
        [HttpPost]
        [Route("config/insert")] // 或 [Route("api/config/insert")]
        public async Task<IActionResult> insert([FromBody] config_file_first_kind dz)
        {

            if (_text == null)
            {
                return StatusCode(500, new { success = false, message = "服务未初始化" });
            }

            try
            {
                int result = await _text.configinsert(dz);
                return Ok(new { success = result > 0, message = result > 0 ? "成功" : "失败" });
            }
            catch (Exception ex)
            {

                Console.WriteLine($"插入异常: {ex.ToString()}"); // 记录完整堆栈
                return StatusCode(500, new { success = false, message = "服务器错误" });
            }

        }
        public IActionResult fy(int currentPage, int pageSize)
        {
            //调用分页的存储过程
            string connectionStr = "server=.;database=HR_DB;uid=sa;pwd=123456;";
            using (SqlConnection conn = new SqlConnection(connectionStr))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@tableName", "ffk_id");
                param.Add("@keyName", "config_file_first_kind");
                param.Add("@currentPage", currentPage);
                param.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYe] @pageSize, @tableName, @keyName, @currentPage, @rows out";
                List<config_file_first_kind> list = conn.Query<config_file_first_kind>(sql, param).ToList();

                FenYe<config_file_first_kind> fenYecs = new FenYe<config_file_first_kind>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("rows");
                //return fenYecs;
                return Json(fenYecs);
            }


        }
    }
}
